import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;

public class Monitor {
    public static void main(String[] args) {
        // 初始化SystemInfo
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystem os = systemInfo.getOperatingSystem();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();

        // 获取所有进程
        for (OSProcess process : os.getProcesses()) {
            // 计算内存占用
            long memoryUsed = process.getResidentSetSize(); // 进程使用的物理内存（字节）
            double memoryPercent = (memoryUsed * 100.0) / systemInfo.getHardware().getMemory().getTotal();

            // 计算CPU占用率
            long processCpuTime = process.getKernelTime() + process.getUserTime();
            long totalCpuTime = processor.getSystemCpuLoadTicks()[CentralProcessor.TickType.SYSTEM.getIndex()];
            double cpuPercent = (processCpuTime * 100.0) / totalCpuTime;

            // 输出进程信息
            System.out.printf("进程: %s (PID: %d)%n",
                    process.getName(),
                    process.getProcessID());
            System.out.printf("内存占用: %.2f MB (%.2f%%)%n",
                    memoryUsed / 1024.0 / 1024.0,
                    memoryPercent);
            System.out.printf("CPU占用率: %.2f%%%n", cpuPercent);
            System.out.println("------------------------");
        }
    }
}